import os
import smtplib
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.header import Header
from Config.Config import Dir


def send_email(reportFile, TO):
    msg = MIMEMultipart()
    msg['From'] = '3083025864@qq.com'  # 发送者邮箱
    msg['To'] = ','.join(TO)  # 接收者邮箱
    msg['Subject'] = Header('订货宝API自动化测试报告', charset='utf8')  # 邮件的标题

    # 添加邮件内容
    text_content = MIMEText('订货宝API自动化测试报告', 'plain', 'utf-8')
    msg.attach(text_content)

    # 添加附件
    annex = MIMEApplication(open(reportFile, 'rb').read())
    annex.add_header('Content-Disposition', 'attachment', filename=reportFile)
    msg.attach(annex)

    # 发送邮件
    smtp = smtplib.SMTP()
    smtp.connect('smtp.qq.com')
    smtplib.SMTP_SSL(host='smtp.qq.com').connect(host='smtp.qq.com')
    smtp.login('3083025864@qq.com', 'xitehxoldxgzddaa')
    smtp.sendmail('3083025864@qq.com', TO, msg.as_string())  # fromAddress,toAddress,msg
    smtp.quit()


# 获取最新报告的地址
def getReportAddress(report):
    reportsList = sorted(os.listdir(report))  # 测试报告文件夹中的所有文件加入到列表
    theLastFile = reportsList[-1]  # 获取最新测试报告文件名称
    reportfile = os.path.join(report, theLastFile)  # 获取最新测试报告文件及路径
    return reportfile


if __name__ == '__main__':
    # 查找最新生成的测试报告
    new_report_addr = getReportAddress(Dir.OrderReport)
    # 自动发送邮件
    TO = ['1308756861@qq.com', '274884591@qq.com', '125414887@qq.com', '1418204211@qq.com']
    send_email(new_report_addr, TO)
